package com.coocaa.x.app.hall.main;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.view.KeyEvent;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.app.hall.HallBaseActivity;
import com.coocaa.x.app.hall.main.ui.PageLayout;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.api.ContentApi;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_hall.RP_ADInfo;
import com.facebook.drawee.backends.pipeline.Fresco;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by luwei on 15-6-16.
 */
public class HallMainActivity extends HallBaseActivity implements SplashView.ShowSplashListener {

    private static final String SPLASH = "splash";
    private SplashView splashView = null;
    private PageLayout layout = null;
    private static boolean frescoShutDown = true;


    @Override
    protected void onActivityStackExit() {
        super.onActivityStackExit();
        logEnd();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Fresco.initialize(CoocaaApplication.getContext());
        frescoShutDown = false;

        if(savedInstanceState != null) {
            hallName = savedInstanceState.getString("name");
            LogUtils.i("hall", "onCreate save: "+hallName);
        } else {
            hallName = getIntent().getStringExtra("name");
            LogUtils.i("hall", "onCreate getStringExtra: "+hallName);
        }

        if (hallName == null || hallName.equals("")) {
            hallName = "kukaishangcheng";
        }


        if (hallName != null && !hallName.equals("")) {
            String url = configSharePreference.getString(getConfigName(SPLASH), "");
            if (!url.equals("")) {
                splashView = new SplashView(this, this);
                splashView.setImageUri(null, Uri.parse(url), 0, 3000);
                setContentView(splashView);
            }
            layout = new PageLayout(this, PageLayout.TitleType.HOME_PAGE);
            layout.refreshLayout(hallName);
            if (url.equals(""))
                setContentView(layout);
            if (Android.isNetConnected(this)) {
                handleAd(hallName);
                post(new Runnable() {
                    @Override
                    public void run() {
                        if (!LiteAppApplication.getFirstLaunch(hallName)) {
                            try {
                                XServiceManager.getLiteCCConnectorService().firstStartAppPoints(hallName);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        logStart();
                    }
                }, 2000);
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
//        moveTaskToBack(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.i("hall", "onResume");
        if (frescoShutDown) {
            LogUtils.i("hall", "onResume Fresco.initialize");
            Fresco.initialize(CoocaaApplication.getContext());
        }

        if (layout != null) {
            layout.onResume();
        }
    }

    @Override
    protected Map<String, String> getPageStartParams() {
        HashMap<String,String> map = new HashMap<String,String>();
        map.put("hallName", hallName);
        return map;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (layout != null)
            layout.onDestroy();
        LogUtils.d("hall", "main activity destory");
//        System.gc();
//        Fresco.shutDown();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (!frescoShutDown)
            Fresco.shutDown();
        Fresco.initialize(CoocaaApplication.getContext());
        frescoShutDown = false;
        String newHallName = intent.getStringExtra("name");
        LogUtils.i("hall", "onNewIntent newHallName : " + newHallName);
        if (newHallName == null || newHallName.equals(""))
            newHallName = "kukaishangcheng";

        hallName = newHallName;

        if (newHallName != null && !newHallName.equals("")) {
            configSharePreference = getSharedPreferences("config", 0);
            String url = configSharePreference.getString(getConfigName(SPLASH), "");
            if (!url.equals("")) {
                splashView = new SplashView(this, this);
                splashView.setImageUri(null, Uri.parse(url), 0, 3000);
                setContentView(splashView);
            }
            if (layout == null)
                layout = new PageLayout(this, PageLayout.TitleType.HOME_PAGE);
            layout.refreshLayout(newHallName);

            if (url.equals(""))
                setContentView(layout);

            if (Android.isNetConnected(this)) {
                handleAd(hallName);
                post(new Runnable() {
                    @Override
                    public void run() {
                        if (!LiteAppApplication.getFirstLaunch(hallName)) {
                            try {
                                XServiceManager.getLiteCCConnectorService().firstStartAppPoints(hallName);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        logStart();
                    }
                }, 2000);
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        LogUtils.i("hall", "onSaveInstanceState hallName = "+hallName);
        outState.putCharSequence("name", hallName);
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    cancelLogTask();
                    Fresco.shutDown();
                    frescoShutDown = true;
                    break;
                case KeyEvent.KEYCODE_HOME:
                    Fresco.shutDown();
                    frescoShutDown = true;
                    break;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void handleAd(final String name) {
        AsyncTask.runOnThread(new Runnable() {
            @Override
            public void run() {
                RP_ADInfo.ADInfo_Item item = ContentApi.getHallAdInfo(name);
                if (item != null)
                    saveSplash(item.picUrl);
                else
                    saveSplash("");
            }
        });
    }

    private void saveSplash(String url) {
        SharedPreferences.Editor editor = configSharePreference.edit();
        editor.putString(getConfigName(SPLASH), url);
        editor.commit();
    }

    @Override
    public void beginShow() {

    }

    @Override
    public void endShow() {
        LogUtils.d("hall", "end show splash");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setContentView(layout);
            }
        });
    }

}
